package org.btik.light.mobile.ui.setting;


import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import org.btik.light.mobile.R;
import org.btik.light.mobile.databinding.FragmentSettingBinding;
import org.btik.light.tool.ByteUtil;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.Objects;

import static android.app.Activity.RESULT_OK;
import static android.content.Context.WIFI_SERVICE;
import static org.btik.light.mobile.platform.conf.AppConfig.LIGHT_SERVER_HOST;
import static org.btik.light.mobile.platform.conf.AppConfig.NAME_SPACE_LIGHT_HANDLER;

public class SettingFragment extends Fragment {

    private FragmentSettingBinding binding;

    ActivityResultLauncher<Intent> setServerLauncher;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        binding = FragmentSettingBinding.inflate(inflater, container, false);
        View root = binding.getRoot();
        showServerHost();
        printIp();
        showWifiInfo();
        setServerLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                this::onSetServer);
        return root;
    }

    /**
     * 刷新设置的server host
     */
    private void onSetServer(ActivityResult result) {
        int resultCode = result.getResultCode();
        if (resultCode == RESULT_OK) {
            showServerHost();
        }
    }

    private void showServerHost() {
        SharedPreferences sharedPreferences = Objects.requireNonNull(getActivity()).getSharedPreferences(NAME_SPACE_LIGHT_HANDLER, Context.MODE_PRIVATE);
        String lightServerHost = sharedPreferences.getString(LIGHT_SERVER_HOST, "");
        TextView cloudServerHost = binding.cloudServerHost;
        if (lightServerHost.isEmpty()) {
            cloudServerHost.setSelected(false);
            cloudServerHost.setText(R.string.not_set);
        } else {
            cloudServerHost.setSelected(true);
            cloudServerHost.setText(lightServerHost);
        }
        cloudServerHost.setOnClickListener(
                (v -> setServerLauncher.launch(new Intent(SetServerHostActivity.NAME))));
    }


    private void showWifiInfo() {
        WifiManager wifiManager = (WifiManager) getActivity().getSystemService(WIFI_SERVICE);
        WifiInfo connectionInfo = wifiManager.getConnectionInfo();
        TextView wifiInfo = binding.wifiInfo;
        int ip = connectionInfo.getIpAddress();
        if (ip != 0) {
            StringBuilder wifiMsg = new StringBuilder();

            wifiMsg.append("\nwifi ssid:")
                    .append(connectionInfo.getSSID()).append("\n本机ip:")
                    .append(ip & 0xff).append('.')
                    .append((ip >> 8) & 0xff).append('.')
                    .append((ip >> 16) & 0xff).append('.')
                    .append((ip >> 24) & 0xff);
            wifiInfo.setText(wifiMsg);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    private void printIp() {
        TextView networkInfo = binding.networkInfo;
        StringBuilder info = new StringBuilder();
        try {

            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            if (networkInterfaces == null) {
                info.append("get no networkInterfaces");
            }
            Resources resources = networkInfo.getResources();
            CharSequence interfaceName = resources.getText(R.string.network_interface_name);
            CharSequence mtuName = resources.getText(R.string.network_interface_mtu);

            while (networkInterfaces != null && networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
                boolean hasIpv4 = false;

                while (inetAddresses.hasMoreElements()) {
                    InetAddress obj = inetAddresses.nextElement();
                    if (!(obj instanceof Inet4Address)) {
                        continue;
                    }
                    if (!hasIpv4) {
                        hasIpv4 = true;
                        String displayName = networkInterface.getDisplayName();
                        info.append(interfaceName).append(displayName);
                        info.append(' ');
                        info.append(mtuName).append(networkInterface.getMTU());
                    }
                    info.append('\n').append(ByteUtil.ipv42Str(obj.getAddress())).append('\n');

                }
            }
            networkInfo.setText(info.toString());


        } catch (Throwable e) {
            e.printStackTrace();
            networkInfo.setText(info.toString());
        }
    }


}